<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { getGoodsRecommend } from '@/api/goods'

const router = useRouter()
const props = defineProps({
  goodsId: {
    type: [String, Number],
    required: true
  }
})

const recommendGoods = ref([])

const loadRecommendGoods = async () => {
  try {
    console.log('🔄 正在加载推荐商品，当前商品ID:', props.goodsId)
    const res = await getGoodsRecommend(props.goodsId)
    recommendGoods.value = (res || []).map(item => ({
      id: item.id,
      name: item.title,
      price: item.price,
      subtitle: item.subtitle || '',
      img: item.image_url || ''
    }))
    console.log('✅ 推荐商品加载完成，共', recommendGoods.value.length, '个')
  } catch (error) {
    console.error('❌ 获取推荐商品失败:', error)
    recommendGoods.value = []
  }
}

const goToDetail = (id) => {
  if (!id) return
  router.push(`/goods/${id}`)
}

const handleImageError = (e) => {
  e.target.src = 'https://via.placeholder.com/200x150?text=暂无图片'
}

// 监听商品ID变化，重新加载推荐商品
watch(() => props.goodsId, (newId, oldId) => {
  if (newId && newId !== oldId) {
    console.log('🔄 检测到商品ID变化,重新加载推荐商品:', oldId, '→', newId)
    loadRecommendGoods()
  }
})

// 组件挂载时加载数据
onMounted(() => {
  loadRecommendGoods()
})
</script>

<template>
  <div class="recommend">
    <h3>猜你喜欢</h3>

    <div v-if="recommendGoods.length === 0" class="no-recommend">
      <el-empty description="暂无推荐商品" />
    </div>

    <div v-else class="recommend-list">
      <div
        v-for="item in recommendGoods"
        :key="item.id"
        class="recommend-item"
        @click="goToDetail(item.id)"
      >
        <div class="image-container">
          <img
            :src="item.img"
            :alt="item.name"
            @error="handleImageError"
            class="goods-image"
          />
        </div>
        <div class="goods-info">
          <h4 class="goods-name">{{ item.name }}</h4>
          <p class="goods-price">¥{{ item.price }}</p>
          <p class="goods-subtitle">{{ item.subtitle || '热销商品' }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.recommend {
  padding: 20px;

  h3 {
    margin-bottom: 20px;
    color: #333;
    font-size: 18px;
    font-weight: bold;
  }
}

.no-recommend {
  text-align: center;
  padding: 40px 0;
}

.recommend-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.recommend-item {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
  cursor: pointer;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }

  .image-container {
    width: 100%;
    height: 150px;
    background: #f5f5f5;
    display: flex;
    align-items: center;
    justify-content: center;

    .goods-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .goods-info {
    padding: 12px;

    .goods-name {
      font-size: 14px;
      color: #333;
      margin-bottom: 8px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .goods-price {
      font-size: 16px;
      color: #ff6b6b;
      font-weight: bold;
      margin-bottom: 4px;
    }

    .goods-subtitle {
      font-size: 12px;
      color: #999;
    }
  }
}
</style>
